package com.sosee.cgfw.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.sosee.cgfw.R;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Thinkpad on 2016/3/1.
 * 注册界面
 */
public class RegisterActivity extends Activity {
    private EditText et_phone;//电话 用户名
    private EditText et_pass;//密码
    private EditText et_pass_ensure;//确认密码
    private EditText et_yanzheng;//验证码
    private EditText et_yaoqing;//邀请码
    private HttpUtils httpUtils;
    private String phone;
    private String pass;
    private String pass_ensure;
    private String yanzheng;
    private String invCode;//邀请码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        initData();
    }


    public void initView(){
        txtView = (TextView)findViewById(R.id.tv_huoqu);
        et_phone= (EditText) findViewById(R.id.et_phone);
        et_phone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus){
                    phone=et_phone.getText().toString().trim();
                    if(phone==null||"".equals(phone)){
                        Utils.showToast(getString(R.string.input_phonenumber));

                    }else{
                        if(!Utils.isMobileNO(phone)){
                            Utils.showToast(getString(R.string.input_right_phonenumber));
                        }else{

                        }
                    }
                }
            }
        });
        et_pass= (EditText) findViewById(R.id.et_pass);
        et_pass.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus){
                    pass=et_pass.getText().toString().trim();
                    if(pass==null||"".equals(pass)){
                        Utils.showToast(getString(R.string.input_pass));
                    }else{
                        if(pass.trim().length()<6){
                            Utils.showToast(getString(R.string.input_pass_count));
                        }
                    }
                }
            }
        });
        et_pass_ensure= (EditText) findViewById(R.id.et_pass_ensure);
        et_pass_ensure.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    et_pass_ensure.setText("");
                }else{
                    ensurePassword();
                }
            }
        });
        et_yaoqing= (EditText) findViewById(R.id.et_yaoqing);
        et_yaoqing.setHint("请输入邀请人的电话");


        et_yanzheng= (EditText) findViewById(R.id.et_yanzheng);
    }

    public void initData(){
        httpUtils=new HttpUtils();
    }

    //点击事件
    public void onClick(View view){
        int id=view.getId();
        switch (id){
            //获取验证码
            case R.id.tv_huoqu:
                getPhone();
                break;
            //注册
            case R.id.rl_zhuce:
                preRegister();
                break;
            case R.id.rl_cancle:
                finish();
                break;
        }
    }


    //验证手机号是否输入 格式是否正确
    public void getPhone(){
        phone=et_phone.getText().toString().trim();
        LogUtils.log_E(phone+"==");
        if(phone!=null&&!"".equals(phone)){
            if(Utils.isMobileNO(phone)){
                getYanzheng();
            }else{
                Utils.showToast(getString(R.string.input_right_phonenumber));
            }
        }else{
            Utils.showToast(getString(R.string.input_phonenumber));
        }
    }
    //密码 和 确认密码 验证
    public boolean ensurePassword(){
        pass=et_pass.getText().toString().trim();
        pass_ensure=et_pass_ensure.getText().toString().trim();
        if(pass!=null && pass.equals(pass_ensure)){
            if(pass.equals("")){
                return false;
            }else{
                return true;
            }

        }else{
            Utils.showToast(getString(R.string.yanzheng_pass));
            return false;
        }
    }


    //注册之前 再次验证
    public void preRegister(){
        phone=et_phone.getText().toString().trim();
        if(TextUtils.isEmpty(phone)){
            Utils.showToast(getString(R.string.input_phonenumber));
        }else{
            if(ensurePassword()){
                yanzheng=et_yanzheng.getText().toString().trim();
                if(yanzheng!=null&&!"".equals(yanzheng)){
                    register();
                }else{
                    Utils.showToast(getString(R.string.input_yanzhengma));
                }
            }
        }
    }



    //获取验证码
    public void getYanzheng(){
        if(txtView.getText().toString().trim().equals("获取")){
            timer=new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    recLen--;
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            };
            //验证码再次发送倒计时
            timer.schedule(task, 1000, 1000);    // timeTask

//        httpUtils.configCurrentHttpCacheExpiry(1000 *1);
            phone=et_phone.getText().toString();
            httpUtils.send(HttpRequest.HttpMethod.GET, Constans.YANZHENG_URL + phone, new RequestCallBack<String>() {

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    LogUtils.log_E("验证码："+responseInfo.result);
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    Utils.showToast(getString(R.string.internet_error));
                }
            });
        }else{

        }

    }
    //注册
    public void register(){
        String tem=et_yaoqing.getText().toString().trim();

        //%@&p=%@&code=%@&inv=%@
        invCode="0";
        if(tem!=null&&!"".equals(tem)){
            invCode=tem;
        }
        httpUtils.configCurrentHttpCacheExpiry(1000 * 1);
        LogUtils.log_E("注册信息"+phone+yanzheng);

        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.REGISTER_URL + phone +"&p="+pass+"&code="+yanzheng+"&inv="+invCode, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                LogUtils.log_E("注册失败信息====="+responseInfo.result);
                try {

                    JSONObject jsonObject=new JSONObject(responseInfo.result);
                    String status=jsonObject.getString("status");
                    if("success".equals(status)){
//                        String userID=jsonObject.getString("userID");
                        //跳转到登陆界面
                        //待定
                        startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
                        finish();
                    }else{
                        Utils.showToast(getString(R.string.register_failed));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast(getString(R.string.internet_error));
            }
        });
    }



    //实现 验证码倒计时功能
    private int recLen = 61;
    private TextView txtView;
    Timer timer = new Timer();

    final Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            switch (msg.what) {
                case 1:
                    txtView.setText(""+recLen);
                    if(recLen < 0){
                        timer.cancel();
//                        txtView.setVisibility(View.GONE);
                        txtView.setText("获取");
                        recLen=61;
                    }
            }
        }
    };



}
